package com.adcc.loadsheet.monitor.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.monitor.entity.MsgAlarmConfig;
import com.adcc.loadsheet.monitor.entity.UDPConfig;
import com.adcc.loadsheet.monitor.service.SystemConfigService;
import com.adcc.loadsheet.monitor.util.Constant;
import com.adcc.loadsheet.monitor.vo.ResultStatus;
import com.adcc.loadsheet.monitor.vo.ResultVO;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 系统配置控制层
 */
@Controller
@RequestMapping(value = "/systemConfig", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SystemConfigController {

    @Autowired
    private SystemConfigService systemConfigService;


    /**
     * 根据系统配置类型获取对应得系统配置详细信息
     *
     * @param configType
     * @return
     */
    @RequestMapping(value = "/getSystemConfig/{configType}", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO getSystemConfig(@PathVariable("configType") String configType) {
        ResultVO vo = new ResultVO();
        try {
            if (!Strings.isNullOrEmpty(configType)) {
                Map<String, Object> configMap = systemConfigService.getSystemConfig(configType);
                vo.getData().put("config", configMap);
            } else {
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(String.format(ResultVO.ER_PARAMS_INVALID, "configType"));
            }

        } catch (Exception ex) {
            Log.error(SystemConfigController.class, "getSystemConfig() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(Constant.ERROR_QUERY, "系统配置信息"));
        }
        return vo;
    }

    /**
     * 保存/更新系统配置
     *
     * @param configType 配置类型
     * @param configMap  配置信息
     * @return
     */
    @RequestMapping(value = "/saveSystemConfig/{configType}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO saveSystemConfig(@PathVariable("configType") String configType, @RequestBody Map<String, Object> configMap) {
        ResultVO vo = new ResultVO();
        try {
            // 校验系统配置数据
            if (validateConfigMap(configType, configMap)) {
                // 校验成功保存系统配置
                systemConfigService.save(configType, configMap);
            } else {
                // 校验失败返回前端提醒参数错误
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(Constant.ERROR_PARAMS);
            }
        } catch (Exception ex) {
            Log.error(SystemConfigController.class, "saveSystemConfig() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(Constant.SAVE_ERROR);
        }
        return vo;
    }


    /**
     * 校验系统配置数据
     *
     *
     * @param configType
     * @param configMap
     * @return
     */
    private boolean validateConfigMap(String configType, Map<String, Object> configMap) {
        boolean result = true;
        try {
            if (!Strings.isNullOrEmpty(configType) && configMap != null && configMap.size() > 0) {
                switch (configType) {
                    case Constant.CONFIG_BGS:
                        if (!configMap.containsKey("healthCheck") || Strings.isNullOrEmpty((String) configMap.get("healthCheck"))) {
                            result = false;
                        }
                        break;
                    case Constant.CONFIG_DATABASE:
                        if (!configMap.containsKey("warn") || Strings.isNullOrEmpty((String) configMap.get("warn"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("error") || Strings.isNullOrEmpty((String) configMap.get("error"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("diskUsage") || Strings.isNullOrEmpty((String) configMap.get("diskUsage"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("tablespaceUsage") || Strings.isNullOrEmpty((String) configMap.get("tablespaceUsage"))) {
                            result = false;
                        }
                        break;
                    case Constant.CONFIG_MQ:
                        if (!configMap.containsKey("url") || Strings.isNullOrEmpty((String) configMap.get("url"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("uplinkTopic") || Strings.isNullOrEmpty((String) configMap.get("uplinkTopic"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("downlinkTopic") || Strings.isNullOrEmpty((String) configMap.get("downlinkTopic"))) {
                            result = false;
                        }
                        break;
                    case Constant.CONFIG_APP_UPLOAD:
                        if (!configMap.containsKey("udp") || configMap.get("udp") == null) {
                            result = false;
                        } else {
                            UDPConfig udpConfig = JSON.parseObject(JSON.toJSONString(configMap.get("udp")), UDPConfig.class);
                            if (Strings.isNullOrEmpty(udpConfig.getHost())
                                    || Strings.isNullOrEmpty(udpConfig.getPort())
                                    || Strings.isNullOrEmpty(udpConfig.getTimeout())) {
                                result = false;
                            }
                        }

                        if (!configMap.containsKey("msgSplit") || configMap.get("msgSplit") == null) {
                            result = false;
                        } else {
                            Map<String, String> msgSplitConfig = (Map<String, String>) configMap.get("msgSplit");
                            if (!msgSplitConfig.containsKey("failureAlarm") || Strings.isNullOrEmpty(msgSplitConfig.get("failureAlarm"))) {
                                result = false;
                            }
                        }

                        if (!configMap.containsKey("ntp") || configMap.get("ntp") == null) {
                            result = false;
                        } else {
                            Map<String, String> ntpConfig = (Map<String, String>) configMap.get("ntp");
                            if (!ntpConfig.containsKey("alarmTime") || Strings.isNullOrEmpty(ntpConfig.get("alarmTime"))) {
                                result = false;
                            }
                        }
                        break;
                    case Constant.CONFIG_AIR_INFO:
                        if (!configMap.containsKey("url") || Strings.isNullOrEmpty((String) configMap.get("url"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("topic") || Strings.isNullOrEmpty((String) configMap.get("topic"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("msgAlarm") || configMap.get("msgAlarm") == null) {
                            result = false;
                        } else {
                            List<MsgAlarmConfig> msgAlarmConfigList = JSON.parseArray(JSON.toJSONString(configMap.get("msgAlarm")), MsgAlarmConfig.class);
                            for (MsgAlarmConfig msgAlarmConfig : msgAlarmConfigList) {
                                if (Strings.isNullOrEmpty(msgAlarmConfig.getName())
                                        || Strings.isNullOrEmpty(msgAlarmConfig.getStartTime())
                                        || Strings.isNullOrEmpty(msgAlarmConfig.getEndTime())
                                        || Strings.isNullOrEmpty(msgAlarmConfig.getTimeout())) {
                                    result = false;
                                    break;
                                }
                            }
                        }
                        break;
                    case Constant.CONFIG_MSG_UP_CENTER:
                        if (!configMap.containsKey("udp") || configMap.get("udp") == null) {
                            result = false;
                        } else {
                            UDPConfig udpConfig = JSON.parseObject(JSON.toJSONString(configMap.get("udp")), UDPConfig.class);
                            if (Strings.isNullOrEmpty(udpConfig.getHost())
                                    || Strings.isNullOrEmpty(udpConfig.getPort())
                                    || Strings.isNullOrEmpty(udpConfig.getTimeout())) {
                                result = false;
                            }
                        }

                        if (!configMap.containsKey("ntp") || configMap.get("ntp") == null) {
                            result = false;
                        } else {
                            Map<String, String> ntpConfig = (Map<String, String>) configMap.get("ntp");
                            if (!ntpConfig.containsKey("alarmTime") || Strings.isNullOrEmpty(ntpConfig.get("alarmTime"))) {
                                result = false;
                            }
                        }

                        if (!configMap.containsKey("lineChart") || configMap.get("lineChart") == null) {
                            result = false;
                        } else {
                            Map<String, String> lineChartConfig = (Map<String, String>) configMap.get("lineChart");
                            if (!lineChartConfig.containsKey("timespan") || Strings.isNullOrEmpty(lineChartConfig.get("timespan"))) {
                                result = false;
                            }

                            if (!lineChartConfig.containsKey("points") || Strings.isNullOrEmpty(lineChartConfig.get("points"))) {
                                result = false;
                            }
                        }
                        break;
                    case Constant.CONFIG_WEBSITE:
                        if (!configMap.containsKey("url1") || Strings.isNullOrEmpty((String) configMap.get("url1"))) {
                            result = false;
                        }

                        if (!configMap.containsKey("url2") || Strings.isNullOrEmpty((String) configMap.get("url2"))) {
                            result = false;
                        }
                        break;
                    case Constant.CONFIG_FORWARDER:
                        if (!configMap.containsKey("healthUrl1") || Strings.isNullOrEmpty((String) configMap.get("healthUrl1"))) {
                            result = false;
                        }
                        if (!configMap.containsKey("healthUrl2") || Strings.isNullOrEmpty((String) configMap.get("healthUrl2"))) {
                            result = false;
                        }
                        break;
                    case Constant.IGNOREALARM:
                        break;
                    case Constant.ROLEDISABLE:
                        break;
                    default:
                        result = false;
                        break;
                }
            } else {
                result = false;
            }
        } catch (Exception ex) {
            Log.error(SystemConfigController.class, "validateConfigMap() error", ex);
            result = false;
        }
        return result;
    }

    /**
     * [2024-6-24：杨家兴：增加运维人员信息详情、增加应急方案详情]
     *
     * @param configType 配置项
     * @param configMap  配置信息
     * @return
     */
    @RequestMapping(value = "/saveRemarkConfig/{configType}", method = RequestMethod.POST)
    @ResponseBody
    public ResultVO saveRemarkConfig(@PathVariable("configType") String configType, @RequestBody Map<String, Object> configMap) {
        ResultVO vo = new ResultVO();
        try {
            // 校验系统配置数据
            if (validateConfigMap(configType, configMap)) {
                //校验成功，保存信息
                systemConfigService.saveRemark(configType, configMap);
                //保存成功返回前端
                vo.setStatus(ResultStatus.SUCCESS);
                vo.getData().put("reason",Constant.SAVE_REMARK_SUCCESS);
            } else {
                //校验失败
                vo.setStatus(ResultStatus.FAILED);
                //保存失败返回前端
                vo.getData().put("reason", String.format(Constant.SAVE_REMARK_ERROR,Constant.ERROR_PARAMS));
            }
        } catch (Exception ex) {
            Log.error(SystemConfigController.class, "saveRemarkConfig() error", ex);
            vo.setStatus(ResultStatus.FAILED);
            //保存失败返回前端
            vo.getData().put("reason", String.format(Constant.SAVE_REMARK_ERROR,ex));
        }
        return vo;
    }

}
